package com.lm.proxy.cglibproxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

// CGLIB 代理类
public class ProductServiceCglibProxy implements MethodInterceptor {
    private final Object target;

    public ProductServiceCglibProxy(Object target) {
        this.target = target;
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("[LOG] Method " + method.getName() + " is called");
        Object result = method.invoke(target, args);
        System.out.println("[LOG] Method " + method.getName() + " execution completed");
        return result;
    }

    public static Object createProxy(Object target) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(new ProductServiceCglibProxy(target));
        return enhancer.create();
    }
}
